<template>
  <div>
    <!-- 面包屑 -->
    <heima-crumbs secondTitle="用户管理" ThirdTitle="用户列表"></heima-crumbs>
    <!-- 卡片搜索区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryParams.query"
            clearable
            @clear="loadUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="loadUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格渲染区 -->
      <el-table
        border
        :data="userList"
        style="width: 1237px"
        class="table"
        stripe
      >
        <el-table-column
          align="center"
          prop="id"
          label="序号"
          width="90"
          type="index"
        ></el-table-column>
        <el-table-column prop="username" label="姓名" align="center">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" align="center">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          align="center"
        ></el-table-column>
        <el-table-column prop="mg_state" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStaterChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="180px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页结构 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      >
      </el-pagination> -->
      <heima-page
        :queryParams="queryParams"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></heima-page>
    </el-card>
    <!-- 添加用户的对话框 -->
    <!-- 3.在对应位置使用模板插槽，并将名字修改 -->
    <heima-dialog
      :addDialogVisible="addDialogVisible"
      @updateList="updateList"
    ></heima-dialog>

    <!-- 编辑用户的对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <!-- 编辑用户表单区域 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 编辑用户底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="showEditDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色会话框 -->
    <el-dialog title="分配角色" :visible.sync="assignRolesVisible" width="30%">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          当前新角色：<el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesVisible">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  updateUserStatus,
  getUserDetail,
  editUser,
  removeUser,
  assignRolesList,
  assignUser
} from '@/api/user'

// 1.引入抽离的组件
import heimaDialog from './user-dialog'
export default {
  name: 'User',
  // 2.局部注册组件
  components: {
    heimaDialog
  },
  data() {
    // 自定义验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // value 就是你要校验的那个值
      // callback 不论是否成功都要调用
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const reMobile = /^1[34578]\d{9}$/
      if (reMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      userList: [],
      editForm: {},
      // 请求参数
      queryParams: {
        query: '', // 查询参数
        pagenum: 1, // 当前页码
        pagesize: 2 // 每页显示条数
      },
      total: 0, // 页面数据总条数
      // 对话框
      addDialogVisible: false,
      editDialogVisible: false,
      assignRolesVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 定义下拉选项框
      selectedRoleId: '',
      // 增加用户验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 监听添加用户对话框的关闭事件
    // addDialogClosed() {
    //   this.$refs.addFormRef.resetFields()
    // },
    updateList() {
      this.addDialogVisible = false
      this.loadUserList()
    },
    async loadUserList() {
      const res = await getUserList(this.queryParams)
      // 将用户数据存到当前组件内，
      // 保存，当前页面总条数
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      this.queryParams.pagesize = val
      this.loadUserList()
    },
    handleCurrentChange(val) {
      this.queryParams.pagenum = val
      this.loadUserList()
    },
    // 监听 switch 开关状态的改变
    async userStaterChanged(userinfo) {
      // console.log(userinfo);
      // 通过更改开关将数据更新到后台
      const res = await updateUserStatus(userinfo)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        userinfo.mg_state = !userinfo.mg_mate
        this.$message.error('更新用户状态失败！')
      }
    },
    // 编辑功能回显
    async edit(id) {
      const res = await getUserDetail(id)
      if (res.meta.status === 200) {
        this.editForm = res.data
      }
      this.editDialogVisible = true
    },
    async showEditDialog() {
      try {
        // 做校验用
        await this.$refs.editFormRef.validate()
        // 请求编辑完成
        const res = await editUser(this.editForm)
        if (res.meta.status === 200) {
          this.$message.success('编辑用户信息成功！')
          this.editDialogVisible = false
        }
        // 加载列表
        this.loadUserList()
      } catch (error) {
        this.$message.error('编辑用户信息失败！')
      }
    },
    // 监听编辑用户对话框的关闭重置事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听编辑用户对话框的关闭重置事件
    // assignRolesClosed() {
    //   this.$refs.editFormRef.resetFields()
    // },
    // 删除功能
    async removeUserById(id) {
      console.log(id)
      // 都要有一个确认提示的操作
      try {
        await this.$confirm('您确定删除该用户吗？')
        // 做真正的删除操作
        const res = await removeUser(id)
        if (res.meta.status !== 200) {
          this.$message.info('您删除失败！')
        } else {
          this.$message.success('您删除成功！')
          this.loadUserList()
        }
      } catch (error) {
        this.$message.error('您取消了删除！')
      }
    },
    // 分配角色
    async assignRoles(userInfo) {
      console.log(userInfo)
      try {
        this.userInfo = userInfo
        // 在展示对话框之前，获取所有角色的列表
        const res = await assignRolesList()
        console.log(res)
        this.rolesList = res.data
        this.assignRolesVisible = true
      } catch (error) {
        this.$message.error('您取消了操作！')
      }
    },
    // 点击按钮，分配角色
    async saveRolesVisible() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择需要分配的角色！')
      }
      const res = await assignUser(this.userInfo.id, this.selectedRoleId)
      if (res.meta.status === 200) {
        this.$message.success('操作成功！')
        this.loadUserList()
        this.selectedRoleId = ''
        this.assignRolesVisible = false
      } else {
        this.$message.error('您取消了操作！')
      }
    }
  },
  // 渲染加载页面
  mounted() {
    this.loadUserList()
  }
}
</script>
<style lang="less">
.table {
  margin-top: 15px;
}
.pagination {
  margin-top: 20px;
}
</style>
